package tr.edu.yildiz.ce.dap.appagent.model;

import org.xml.sax.Attributes;

public abstract class XMLModel {

	public abstract void init(Attributes attributes);
	public abstract void writeXML(StringBuilder sBuilder);
	public abstract String getXmlNodeName();
	
	private boolean hasChild = false;
	private StringBuilder innerSBuilder = new StringBuilder();
	private StringBuilder attrSBuilder = new StringBuilder();
	
	public String toXML(){
		innerSBuilder = new StringBuilder();
		attrSBuilder = new StringBuilder();
		StringBuilder sBuilder = new StringBuilder();
		writeXML(sBuilder);
		writeAttributesAndValue(sBuilder);
		return sBuilder.toString();
	}
	
	protected void writeAttributesAndValue(StringBuilder sBuilder){
		sBuilder.append("<");
		sBuilder.append(getXmlNodeName());
		sBuilder.append(attrSBuilder);
		if (hasChild){
			sBuilder.append(">");
			sBuilder.append(innerSBuilder);
			sBuilder.append("</");
			sBuilder.append(getXmlNodeName());
			sBuilder.append(">");
		}else {
			sBuilder.append("/>");
		}
	}
	
	protected void addChild(XMLModel model){
		if (model == null)
			return;
		hasChild = true;
		innerSBuilder.append(model.toXML());
	}
	
	protected void addChildStr(String name,Object value){
		if (value == null)
			return;
		hasChild = true;
		innerSBuilder.append("<");
		innerSBuilder.append(name);
		innerSBuilder.append(">");
		innerSBuilder.append(value.toString());
		innerSBuilder.append("</");
		innerSBuilder.append(name);
		innerSBuilder.append(">");
	}
	
	protected void addAttribute(StringBuilder sBuilder,String name,String value){
		if (value == null)
			return;
		attrSBuilder.append(" ");
		attrSBuilder.append(name);
		attrSBuilder.append("=");
		attrSBuilder.append("\"");
		attrSBuilder.append(value);
		attrSBuilder.append("\"");
	}
	
	
}
